# JellyBeanColourCounter.py # # Description: This program takes an image as input and outputs # the percentage of each jellybean colour in the image. # # Author: AL and AL # Date: March 2024 # Import image processing libraries from PIL import Image # Import myColourModule import myColourModule # ***Main part of the program # Open an image of jellybeans and load its bitmap jellyBeansOpen = Image.open("jelly_beans.jpg") jellyBeansLoad = jellyBeansOpen.load() # Create a list to store the pixels that are yellow yellowPixelList = [] yellowPixelCount = 0 # Get dimensions of bitmap width = jellyBeansOpen.width height = jellyBeansOpen.height # Go through all the pixels in the image for j in range(height): for i in range(width): r = jellyBeansLoad[i,j][0] g = jellyBeansLoad[i,j][1] b = jellyBeansLoad[i,j][2] # If it's yellow, then add that pixel to the yellow list # if myColourModule.isPixelYellow(r, g, b): if myColourModule.isPixelYellow((r, g, b)): yellowPixelList.append(jellyBeansLoad[i,j]) # Improvement: using a running count of the yellow pixels # instead of accumulating the yellow pixels into a list yellowPixelCount += 1 # Get the length of the yellow pixel list numberOfYellowPixels = len(yellowPixelList) # Compute the total number of pixels in the image numberOfTotalPixels = height * width # Calculate the percentage of yellow pixels over the # total number of pixels in the image percentYellow = 100 * (numberOfYellowPixels / numberOfTotalPixels) percentYellow2 = 100 * (yellowPixelCount / numberOfTotalPixels) # Output a report print(f'There are: {percentYellow:.2f}% yellow jellybeans in the batch.') print(f'There are: {percentYellow2:.2f}% yellow jellybeans in the batch.') # Close the file jellyBeansOpen.close()